package com.csj.mvvm.utils

import android.app.Activity
import java.util.*

class AppManager {
    private var activityStack: Stack<Activity> = Stack()

    //懒汉
    companion object {
        val instance: AppManager by lazy(mode = LazyThreadSafetyMode.PUBLICATION) {
            AppManager()
        }
    }
    //懒汉
//    companion object {
//        private var instance: AppManager? = null
//        fun getInstance() = instance ?: AppManager().also { instance = it }
//    }

    //饿汉
//    companion object {
//        val instance = SingletonHolder.holder
//    }
//
//    private object SingletonHolder {
//        val holder = AppManager()
//    }

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity?) {
        activityStack.add(activity)
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity? {
        try {
            return activityStack.lastElement()
        } catch (e: NoSuchElementException) {
            e.fillInStackTrace()
        }
        return null
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        var activity: Activity? = null
        try {
            activity = activityStack.lastElement()
        } catch (e: NoSuchElementException) {
            e.fillInStackTrace()
        }
        activity?.finish()
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            activityStack.remove(activity)
            activity.finish()
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (i in activityStack.indices) {
            if (activityStack[i] == cls) {
                finishActivity(activityStack[i])
                break
            }
        }
    }

    /**
     * 结束所有Activity
     */
    private fun finishAllActivity() {
        for (i in activityStack.indices) {
            if (null != activityStack[i]) {
                activityStack[i].finish()
            }
        }
        activityStack.clear()
    }

    /**
     * 退出应用程序
     */
    fun appExit() {
        try {
            finishAllActivity()
//            Process.killProcess(Process.myPid())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}